package com.kazm.toolkit.excel;

import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;

public class WriteToExcel {
	public void writeObjectsToExcel(String path, List<Object> list) {
		HSSFWorkbook workbook = new HSSFWorkbook();
		HSSFSheet sheet = workbook.createSheet("Result");
		int rownum = 0;
		int cellnum = 0;
		Row row = null;
		Cell cell;
		for (Object ob : list) {
			row = sheet.createRow(rownum++);
			for (Field field : ob.getClass().getDeclaredFields()) {
				field.setAccessible(true);
				String name = field.getName();
				Object value = null;
				try {
					value = field.get(ob);
				} catch (IllegalArgumentException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IllegalAccessException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				cell = row.createCell(cellnum++);
				cell.setCellValue((String) value);
			}
			cellnum = 0;
		}

		try {
			FileOutputStream out = new FileOutputStream(new File(path));
			workbook.write(out);
			out.close();
			System.out.println("Excel written successfully..");

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
